// 全局常量：全部大写，多个单词之间使用下划线分割 const GOODS_TYPE =1
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
// executor:接收的执行器函数
function Promise(executor){
	// 设置初始状态
	this.state = PENDING;
	// 设置初始状态值
	this.result = undefined;
	// 用于调用成功与失败回调的属性
	this.callback = [];
	function _resolve(v){
		// 判断状态是否已经被更改
		if(this.state !== PENDING) return;
		this.state = FULFILLED;
		this.result = v;
		this.callback.forEach(item=>item.onResolved());
	}
	function _reject(v){
		if(this.state !== PENDING) return;
		this.state = REJECTED;
		this.result = v;
		this.callback.forEach(item=>item.onRejected());
	}
	try{
		// 调用执行器函数，并传递两个参数（类型为函数）
		executor(_resolve.bind(this),_reject.bind(this));
	}catch (err){
		_reject.call(this,err);
	}
}
Object.assign(Promise.prototype,{
	// onResolved:成功回调
	// onRejected:失败回调
	then(onResolved,onRejected){
		// 判断onResolved是否为函数,如果不是函数设置默认值
		if(!(onResolved instanceof Function)){
			onResolved = value=>value;
		}
		if(!(onRejected instanceof Function)){
			onRejected = reason=>{
				throw reason;
			}
		}
		
		// 返回了一个新的Promise实例
		return new Promise((resolve,reject)=>{
			// 封装
			const _common = function(callback){
				setTimeout(()=>{
					try{
						const value = callback(this.result);
						if(value instanceof Promise) value.then(resolve,reject)
						else resolve(value);
					}catch (e){
						reject(e);
					}
				})
			}
			// 状态为fulfilled调用onResolved
			// 状态为rejected调用onRejected
			if(this.state === FULFILLED){
				_common.call(this,onResolved);
			}else if(this.state === REJECTED){
				_common.call(this,onRejected)
			}else if(this.state === PENDING){// 1
				// 记录如果状态更改为成功需要调用的函数
				// 记录如果状态更改为失败需要调用的函数
				this.callback.push({
					onResolved:_common.bind(this,onResolved),
					onRejected:_common.bind(this,onRejected)
				})
			}
		})
		
	}
})